from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.template.context_processors import csrf
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User, Group
from .models import Report, Lab_record
from datetime import datetime
from home.context_processors import hasGroup
from appointments.models import Appointment
from case.models import case
from django.contrib import messages
from bill.models import bill
from django.utils import timezone
# Create your views here.
from appointments.views import BookingFormQueue
from appointments.views import wait_array


# RETRIEVE
@login_required
def view_reports(request):
    c = {}
    c.update(csrf(request))
    if hasGroup(request.user, 'lab_doctor'):
        user = request.user
        c['reports'] = Lab_record.objects.filter(
            lab_item__manufacturer__department_name=user.lab_doctor.lab_department.department_name).order_by(
            '-lab_created_time')
        c['isLab_doctor'] = True

        return render(request, 'report/view.html', c)

        # for cases in case.objects.filter(patient=request.user):
        # c['bills'].extend(list(bill.objects.filter(case=cases)))
    elif hasGroup(request.user, 'patient'):
        user = request.user
        c['reports'] = Lab_record.objects.filter(case__patient__username=user.username)
        c['is_Patient'] = True
        return render(request, 'report/view.html', c)
    else:
        messages.add_message(request, messages.WARNING, 'Access Denied.')
        return HttpResponseRedirect('/home')

@login_required
def doctor_view_reports(request,case_id):
    if hasGroup(request.user, 'doctor'):
        c = {}
        c.update(csrf(request))
        c['reports'] = Lab_record.objects.filter(case_id=case_id)
        print(Lab_record.objects.filter(case_id=case_id))
        c['doctor'] = True
        return render(request, 'report/view.html', c)
    else:
        messages.add_message(request, messages.WARNING, 'Access Denied.')
        return HttpResponseRedirect('/home')


@login_required
def view_pdf(request, lab_file_name):
    c = {}
    c.update(csrf(request))
    if hasGroup(request.user, 'patient') or hasGroup(request.user, 'lab_doctor') or hasGroup(request.user, 'doctor'):
        # lab = Lab_record.objects.get(id=lab_id)
        c['pdf_name'] = lab_file_name
        print(c['pdf_name'])
        return render(request, 'report/view_pdf.html', c)
    else:
        messages.add_message(request, messages.WARNING, 'Access Denied.')
        return HttpResponseRedirect('/home')
    #if hasGroup(request.user, 'lab_doctor'):
        #return render(request,"D:\\pycharm_codes\\his_git\\HIS2020\\my_hospital\\home\\static\\pdf_static\\report_pdf\\" + lab_file_name)



# CREATE
@login_required
def generate(request, bill_id):
    if hasGroup(request.user, 'lab_doctor'):
        bill_update = bill.objects.get(id=int(bill_id))
        bill_update.is_processed = True
        bill_update.save()

        c = {}
        c.update(csrf(request))
        bill_to_report = bill.objects.get(id=int(bill_id))
        c['bill'] = bill_to_report
        c['case'] = case.objects.get(id=int(bill_to_report.case_id))
        return render(request, 'report/generate.html', c)
    messages.add_message(request, messages.WARNING, 'Access Denied.')
    return HttpResponseRedirect('/home')


@login_required
def doGenerate(request):
    if hasGroup(request.user, 'lab_doctor'):
        bill_temp_id = request.POST.get('bill_id', '')
        bill_temp = bill.objects.get(id=int(bill_temp_id))

        description = request.POST.get('report_description', '')
        print(description)
        report_file = request.FILES.get('report_file', '')
        if report_file:
            path = "./home/static/pdf_static/report_pdf/" + report_file.name
            with open(path, 'wb+') as f:
                for chunk in report_file.chunks():
                    f.write(chunk)

        generated_date = timezone.now()

        report_case = case.objects.get(id=int(bill_temp.case.id))
        print(type(bill.case))
        report = Lab_record(lab_id=str(bill_temp.case.patient.username + str(timezone.now())),
                            lab_description=description,
                            lab_item=bill_temp.item,
                            lab_operator=request.user,
                            lab_created_time=generated_date,
                            lab_result=report_file.name,
                            case=report_case)
        report.save()
        messages.add_message(request, messages.INFO, 'Report Successfully Generated.')
        return HttpResponseRedirect('/reports')
    messages.add_message(request, messages.WARNING, 'Access Denied.')
    return HttpResponseRedirect('/home')


# RETRIEVE
@login_required
def view(request):
    c = {}
    user = request.user
    if hasGroup(user, 'lab_doctor'):
        c['isLab_doctor'] = True
        list1 = bill.objects.filter(bill_create_date__day=timezone.now().day,
                                    bill_create_date__month=timezone.now().month,
                                    bill_create_date__year=timezone.now().year,
                                    is_processed=False,
                                    item__manufacturer__department_name=user.lab_doctor.lab_department.department_name,
                                    is_paid=True
                                    ).order_by('bill_paid_date')
        c['waiting_labs'] = list1

        return render(request, 'report/view_doctor.html', c)
    elif hasGroup(user, 'patient'):
        c['reports'] = [report for report in Report.objects.all() if report.case.patient == request.user]
        return render(request, 'report/view.html', c)
    else:
        messages.add_message(request, messages.WARNING, 'Access Denied.')
        return HttpResponseRedirect('/home')


# UPDATE
@login_required
def change(request, id):
    '''user = request.user
    if hasGroup(user, 'lab_attendant'):

        return render(request, 'report/change.html', c)
    messages.add_message(request, messages.WARNING, 'Access Denied.')'''
    return HttpResponseRedirect('/home')


@login_required
def doChange(request):
    pass


# DELETE
@login_required
def delete(request, id):
    user = request.user
    if hasGroup(user, 'lab_attendant'):
        Report.objects.get(id=id).delete()
    return HttpResponseRedirect('/home')


def for_pdf(request):
    return render(request, 'report/view_pdf.html')
